/*
 * IPHandle.java
 *
 * Created on 23 de Dezembro de 2004, 15:00
 */

package ceirinhashls.util;
import java.text.MessageFormat;
/**
 *
 * @author  botelhodaniel
 */
public class IPHandle {
    public static final int DEFAUL_PORT = 411;
    
    public static boolean isLocalMachine(String ip){
        if(ip.equalsIgnoreCase("127.0.0.1") || ip.equalsIgnoreCase("localmachine"))
            return true;
        return false;
    }
    
    public static String removeMultiplePorts(String str){
        String s = str.trim();
        if(s.indexOf(":")<0)
            return s;
        else if(s.indexOf(":")==s.lastIndexOf(":"))
            return s;
        else
            return s.substring(0,s.indexOf(":"))+s.substring(s.lastIndexOf(":"),s.length());
    }
    public static String removePort(String str){
        String s = str.trim();
        if(s.indexOf(":")<0)
            return s;
        else
            return s.substring(0,s.indexOf(":"));
    }
    public static boolean hasPort(String ip){
        return !(ip.indexOf(":")<0);
    }
    public static boolean hasMultiplePorts(String ip){
        return ip.indexOf(":") != ip.lastIndexOf(":");
    }
    
    public static int getPort(String ip){
        String s = removeMultiplePorts(ip.trim());
        if(hasPort(s))
            return new Integer(s.substring(s.indexOf(":")+1)).intValue();
        else
            return DEFAUL_PORT;
    }
    
    public static Long IPtoIPRange(String ip) throws Exception{
        MessageFormat ipFromat = new MessageFormat("{0}.{1}.{2}.{3}");
        Object[] obj = ipFromat.parse(ip);
        long ipRange = new Long(""+obj[3]).longValue();
        ipRange += new Long(""+obj[2]).longValue()*256;
        ipRange += new Long(""+obj[1]).longValue()*65536;
        ipRange += new Long(""+obj[0]).longValue()*16777216;
        return new Long(ipRange);
    }

}
